<template>
  <view class="helper-page">
    <view class="header">
      <view class="title">{{ title }} {{ $t('zhuShouHelper.selectedCount', { count: selectedItems.length }) }}</view>
      <button class="close-btn" @click="handleClose">{{ $t('zhuShouHelper.close') }}</button>
    </view>
    
    <!-- 分组筛选 -->
    <view class="filter-bar">
      <view class="filter-label">{{ $t('zhuShouHelper.category') }}:</view>
      <view class="filter-value" @click="toggleTypeSheet">
        {{ currentGroupName }}
        <text class="dropdown-arrow">▼</text>
      </view>
    </view>
    
    <!-- 选项列表 -->
    <scroll-view scroll-y class="option-list">
      <view v-if="loading" class="loading-state">
        <text>{{ $t('zhuShouHelper.loading') }}</text>
      </view>
      <view v-else-if="filteredOptions.length === 0" class="no-data-state">
        <text>{{ $t('zhuShouHelper.noData') }}</text>
      </view>
      <view 
        v-else
        v-for="item in filteredOptions" 
        :key="item.id" 
        class="option-item" 
        :class="{ 'selected': isItemSelected(item) }"
        @click="toggleItem(item)"
      >
        <view class="checkbox" :class="{ 'checked': isItemSelected(item) }">
          <text v-if="isItemSelected(item)" class="checkmark">✓</text>
        </view>
        <text class="option-label">{{ item.name }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getAssistant } from '@/api/order.js';
import { useI18n } from 'vue-i18n';

export default {
  data() {
    return {
      title: '助手',
      type: '',
      selectedItems: [],
      groupOptions: [],
      groupIds: [],
      groupIndex: 0,
      allOptions: [],
      innerOptions: [],
      showDropdown: false,
      loading: false
    }
  },
  
  setup() {
    const { t } = useI18n();
    return { t };
  },
  
  computed: {
    // 当前选中的分组名称
    currentGroupName() {
      if (this.groupIndex === 0) return this.t('zhuShouHelper.all');
      return this.groupOptions[this.groupIndex] || this.t('zhuShouHelper.all');
    },
    
    // 根据分组过滤选项
    filteredOptions() {
      if (this.groupIndex === 0) {
        return this.innerOptions;
      }
      const groupId = this.groupIds[this.groupIndex];
      return this.innerOptions.filter(opt => opt.sub_type === groupId);
    }
  },
  
  onLoad(options) {
    this.type = options.type || '';
    this.title = options.title || '助手';
    
    // 初始化已选择的项目
    this.initSelectedItems(options);
    
    // 获取数据
    this.fetchData();
  },
  
  methods: {
    // 初始化已选择的项目
    initSelectedItems(options) {
      const storageKey = 'helper_selected_' + (this.type || 'default');
      
      if (options.selected) {
        try {
          // 从主页面传递过来的数据
          const selectedData = JSON.parse(decodeURIComponent(options.selected));
          this.selectedItems = Array.isArray(selectedData) ? selectedData : [];
          // 保存到本地存储
          uni.setStorageSync(storageKey, this.selectedItems);
        } catch (e) {
          console.error('解析selected参数失败:', e);
          this.selectedItems = [];
        }
      } else {
        // 从本地存储获取
        const localSelected = uni.getStorageSync(storageKey);
        this.selectedItems = (localSelected && Array.isArray(localSelected)) ? localSelected : [];
      }
    },
    
    // 获取数据
    async fetchData() {
      this.loading = true;
      try {
        const res = await getAssistant(this.type);
        if (res.code === 200 && res.success) {
          // 处理分组数据
          this.groupOptions = [this.t('zhuShouHelper.all'), ...(res.result.sub_type_list || []).map(g => g.type)];
          this.groupIds = [null, ...(res.result.sub_type_list || []).map(g => g.id)];
          
          // 处理选项数据
          this.allOptions = res.result.item || [];
          this.innerOptions = this.allOptions.map(item => ({
            id: item.id,
            name: item.name,
            code: item.code,
            sub_type: item.sub_type,
            type: item.type,
            describe: item.describe
          }));
          
          this.groupIndex = 0;
        } else {
          uni.showToast({ 
            title: res.message || this.t('zhuShouHelper.dataLoadFailed'), 
            icon: 'none' 
          });
        }
      } catch (e) {
        console.error('获取数据失败:', e);
        uni.showToast({ 
          title: this.t('zhuShouHelper.networkError'), 
          icon: 'none' 
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 切换分组
    toggleTypeSheet() {
      uni.showActionSheet({
        itemList: this.groupOptions,
        success: (res) => {
          this.groupIndex = res.tapIndex;
        }
      });
      this.showDropdown = false;
    },
    
    // 检查项目是否被选中
    isItemSelected(item) {
      return this.selectedItems.some(selected => {
        if (typeof selected === 'object' && selected.id) {
          return selected.id === item.id;
        } else {
          return selected === item.id;
        }
      });
    },
    
    // 切换选择状态
    toggleItem(item) {
      const isSelected = this.isItemSelected(item);
      
      if (isSelected) {
        // 移除选中项
        this.selectedItems = this.selectedItems.filter(selected => {
          if (typeof selected === 'object' && selected.id) {
            return selected.id !== item.id;
          } else {
            return selected !== item.id;
          }
        });
      } else {
        // 添加选中项
        const newItem = {
          id: item.id,
          name: item.name,
          code: item.code,
          sub_type: item.sub_type,
          type: item.type
        };
        this.selectedItems = [...this.selectedItems, newItem];
      }
      
      // 保存到本地存储
      const storageKey = 'helper_selected_' + (this.type || 'default');
      uni.setStorageSync(storageKey, this.selectedItems);
      
      // 强制更新视图
      this.$forceUpdate();
    },
    
    // 关闭页面
    handleClose() {
      // 保存选择结果
      const storageKey = 'helper_selected_' + (this.type || 'default');
      uni.setStorageSync(storageKey, this.selectedItems);
      
      // 通过事件通道回传数据
      const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
      if (eventChannel) {
        eventChannel.emit('helperSelected', this.selectedItems);
      }
      
      // 返回上一页
      const pages = getCurrentPages();
      if (pages.length <= 1) {
        uni.reLaunch({ url: '/pages/order/index' });
      } else {
        uni.navigateBack();
      }
    }
  }
}
</script>

<style scoped>
.helper-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f8f8f8;
}

.header {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32rpx 32rpx 24rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  min-height: 88rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.close-btn {
  position: absolute;
  top: 16rpx;
  right: 32rpx;
  font-size: 28rpx;
  color: #1976d2;
  background: #fff;
  border: 1rpx solid #eee;
  border-radius: 6rpx;
  padding: 8rpx 16rpx;
  z-index: 10;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.filter-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 32rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.filter-label {
  color: #666;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.filter-value {
  color: #1976d2;
  font-size: 28rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.dropdown-arrow {
  margin-left: 8rpx;
  font-size: 24rpx;
  color: #999;
}

.option-list {
  flex: 1;
  padding: 16rpx;
  background: #f8f8f8;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 12rpx;
  background: #fff;
  border-radius: 12rpx;
  cursor: pointer;
  transition: all 0.2s;
}

.option-item.selected {
  background: #e3f2fd;
  border: 1rpx solid #1976d2;
}

.option-item:active {
  background: #f0f4fa;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  transition: all 0.2s;
}

.checkbox.checked {
  border-color: #1976d2;
  background: #1976d2;
}

.checkmark {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.option-label {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  line-height: 1.4;
}

.loading-state,
.no-data-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60rpx 20rpx;
  color: #999;
  font-size: 28rpx;
}

.loading-state {
  color: #1976d2;
}
</style>